package com.gxks.lhs.security;

import com.alibaba.fastjson2.JSON;
import com.gxks.lhs.constants.Constants;
import com.gxks.lhs.constants.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author LuoHaisong
 */
@Slf4j
@Component
public class NotLoginPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.warn(">>>>>>>>>>" + authException.getMessage());
//        String jsonR = JSON.toJSONString(R.error(401, "未登录或登录已失效，请重新登录"));
//        response.setContentType("application/json");
//        response.getWriter().print(jsonR);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 这里根据你的需求构造并返回JSON格式的错误信息
        String errorMessage = JSON.toJSONString(R.error(0, authException.getMessage()));
        response.getWriter().write(errorMessage);
    }

}